package com.xxl.util;

import com.xxl.dto.UserDto;
import com.xxl.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Random;

/**
 *  邮件工具类
 * @author xxl
 * @date  2023/4/3
 */
@Component
@Slf4j
public class EmailUtil {
    @Value("${emailAddress}")
    public String from;
    private String code = new Random().nextInt(999999)+"";
    @Resource
    public JavaMailSenderImpl javaMailSender;
    @Resource
    UserService userService;

    @Async
    public  void sendEmail(String to) {
        log.info("验证码="+code);
        //查询总共有多少用户
        List<UserDto> userList = userService.queryAllUser();
        //邮件对象
        SimpleMailMessage message = new SimpleMailMessage();
        //设置邮件主体
        message.setSubject("博客注册");
        //设置邮件内容
        message.setText("<h2 style='color: red'>欢迎注册blog应用,您是blog应用的第"+userList.size()
                +"位用户</h2><br><p style='color: deepskyblue;font-size: 20px'>注册码:"+code+"</p>");
        //发给谁
        message.setTo(to);
        //谁来发
        message.setFrom(from);
        //发送邮件
        javaMailSender.send(message);
    }

    public String getCode() {
        return code;
    }
}
